package com.sline.day03._02_smis.dao.impl;

import com.sline.day03._02_smis.dao.IStudentDao;
import com.sline.day03._02_smis.domain.Student;
import com.sline.day03._02_smis.template.JdbcTemplate;
import com.sline.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

public class StudentDaoImpl implements IStudentDao {
    @Override
    public void save(Student student) {
        String sql = "insert into t_student (name, age) values(?, ?);";

        JdbcTemplate.update(sql, student.getName(), student.getAge());
    }

    @Override
    public void delete(Long id) {
        String sql = "delete from t_student where id = ?;";

        JdbcTemplate.update(sql, id);
    }

    @Override
    public void update(Long id, Student student) {
        // update t_student name = 'name', age = age where id = id;

        String sql = "update t_student set name = ?, age = ? where id = ?";

        JdbcTemplate.update(sql, student.getName(), student.getAge(), id);
    }

    @Override
    public Student get(Long id) {

        String sql = "select * from t_student where id = ?;";

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
            connection = JdbcUtil.getConnection();

            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setLong(1, id);

            rs = preparedStatement.executeQuery();
            if (rs.next()) {
                Student st = new Student();

                st.setSid(rs.getLong("id"));
                st.setName(rs.getString("name"));
                st.setAge(rs.getInt("age"));

                return st;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(connection, preparedStatement, rs);
        }

        return null;
    }

    @Override
    public ArrayList<Student> list() {
        String sql = "select * from t_student";
        ArrayList<Student> arrayList = new ArrayList<>();

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet rs = null;
        try {
            connection = JdbcUtil.getConnection();

            preparedStatement = connection.prepareStatement(sql);

            rs = preparedStatement.executeQuery();
            while (rs.next()) {
                Student st = new Student();

                st.setSid(rs.getLong("id"));
                st.setName(rs.getString("name"));
                st.setAge(rs.getInt("age"));

                arrayList.add(st);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(connection, preparedStatement, rs);
        }

        return arrayList;
    }
}
